#!/usr/bin/env python
import xg
import getopt
import sys
from getpass import getpass

def usage():
  print "USAGE:"
  print "checkGrid.py [options]";
  print "Required options:"
  print "-h <hostname>";
  print "";
  print "Optional:";
  print "-g <grid id>";

def main():
  # Get command line arguments. 
  try:
    opts, args = getopt.getopt(sys.argv[1:], "h:g:")
  except getopt.GetoptError:
    usage();
    sys.exit(1)
  
  hostname = None;
  gridid = None;
  for o,a in opts:
    if o == "-h":
      hostname = str(a);
    
    if o == "-g":
      gridid = str(a);
      
  # Did we get a hostname?
  if not hostname:
    print "You must supply a hostname with -h."
    print "";
    usage();
    sys.exit(1);
    
  # Did we get a grid?
  if not gridid:
    gridid = 0;
    
  # Ask for the grid password. 
  print "Xgrid authentication..";
  passw = getpass();
  
  # Connect to the grid.
  try:
    contr = xg.Controller(xg.Connection(hostname = str(hostname),password = str(passw)));
    grid = contr.grid(gridid);
  except:
    print "An error occurred while connecting to the grid."
    print "This is probably due to an incorrect password.";
    print "The actual error thrown was:"
    print "";
    raise;
  
  # Check jobs.
  print "Pinging grid (this could take a few minutes)..";
  jobCount = 0;
  numFinished = 0;
  for job in grid.jobs():
    if job.info()['jobStatus'] == 'Finished':
      numFinished += 1;
    
    jobCount += 1;
  
  # Print results.
  percentComplete = float(numFinished) * 100 / jobCount;
  print "Number of jobs on grid: " + str(jobCount);
  print "Number of jobs remaining: " + str(jobCount - numFinished);
  print "Percent complete: " + str(percentComplete);

if __name__ == "__main__":
  main();
